import { NzMessageService } from 'ng-zorro-antd/message';
import { AbsFormUtil } from '@abstract/form';
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { LoginService } from '@service/login.service';
import { Router, ActivatedRoute } from '@angular/router';
import { TreeService } from '@service/tree.service';
import { AuthService } from '@service/auth.service';

@Component({
	selector: 'app-login',
	templateUrl: './login.component.html',
	styleUrls: ['./login.component.less']
})
export class LoginComponent extends AbsFormUtil implements OnInit {
	validateForm: FormGroup;
	nzLoading = false;
	redirectUrl = '/page/home';

	menuList = [];
	constructor(
		private fb: FormBuilder,
		private loginService: LoginService,
		private nzMessageService: NzMessageService,
		private router: Router,
		private route: ActivatedRoute
	) {
		super();
		this.redirectUrl = this.route.snapshot.queryParamMap.get('redirectUrl');
	}

	ngOnInit() {
		this.buildForm();
		const loginInfo = this.loginService.getLoginInfo();
		if (loginInfo) {
			this.validateForm.patchValue(loginInfo);
		}
	}

	async onSubmit() {
		this.markAsDirty();
		if (!this.validateForm.valid) {
			return;
		}
		if (this.validateForm.value.remember) {
			this.loginService.saveLoginInfo(this.validateForm.value);
		}else {
			this.loginService.removeLoginInfo();
		}
		this.nzLoading = true;
		const messageId = this.nzMessageService.loading('登录中, 请稍后', {nzDuration: 0});
		const validateForm = this.validateForm.value;
		const result = await this.loginService.login(validateForm);
		this.nzLoading = false;
		this.nzMessageService.remove(messageId.messageId);
		if (result.code === 500) {
			this.nzMessageService.error(result.msg);
			return;
		}
		this.loginService.saveUserInfo(result.data);
		this.router.navigateByUrl(this.redirectUrl);
		this.nzLoading = false;
	}


	buildForm() {
		this.validateForm = this.fb.group({
			loginName: [null, [Validators.required]],
			password: [null, [Validators.required]],
			remember: [false]
		});
	}

	
	
}
